FOOTBALL ANALYTICS — CURRENT APPLICATION GUIDE
Updated 12 November 2026
=============================================

This project manages football match records, evaluates an automated strategy
lifecycle, and reports results through Plan 1, Plan 2 and one combined
Analytics view. Historical results describe past data; they do not guarantee
future performance.

CURRENT PAGE ROLES
------------------
Overview
  Live workspace summary and shortcuts.

Matches
  Search, inspect, add, edit and delete match records. Changes save to the
  SQLite registry and synchronize the workbook mirror.

Strategies
  Emerging Strategy Lab studies candidates. Strategy Performance Manager is
  the authority for Active strategies and their automatic promotion,
  continued qualification and return to the Lab.

Plan 1
  Matches with exactly one currently Active Manager trigger. Includes a
  cumulative performance graph, drawdown and chronological analysis.

Plan 2
  Matches with two or more currently Active Manager triggers, evaluated as a
  multi-strategy combination. Includes performance and risk panels.

Analytics
  One combined Plan 1 + Plan 2 view. Each qualifying match appears once with
  its Plan label, plus combined drawdown and chronological evaluation.

Data & Notes
  Read-only audit/export for match records, browser-local research notes and
  the current project guide, including the five-rule lifecycle and risk tools.

SOURCE OF TRUTH AND STORAGE
---------------------------
- football_analytics.db is the canonical match registry.
- SOCCER_RATING.xlsx seeds an empty database on first setup. After
  initialization, the app synchronizes the workbook from SQLite at startup
  and after supported record changes. Editing the workbook directly does not
  update live records.
- Data & Notes reads /api/matches and /api/health; it does not edit match data.
- Manager status and research notes are stored in browser local storage for
  the app origin. They are separate from the SQLite database and workbook.
- Data & Notes JSON backup/import and notes CSV apply only to notes. JSON
  import replaces the notes saved in that browser.

AUTOMATIC STRATEGY LIFECYCLE
----------------------------
All FIVE rules are mandatory for qualification in the shared browser lifecycle:
1. At least 50 settled matches.
2. Historical net strictly greater than GH₵1,000.
3. Historical ROI strictly greater than 0%.
4. Net strictly greater than GH₵0 across the latest 20 settled matches.
5. Performance Score at least 50/100.

The fixed-reference, capped Performance Score uses historical ROI (40%),
recent-20 net (35%), sample size (15%), and historical net (10%). It is a
historical heuristic, not a forecast probability. Complete settlement prices
are also necessary for qualification.

The Lab and Manager evaluate automatically from loaded match data. A candidate
passing every rule becomes Active. If an Active strategy fails any rule, it
immediately returns to the Lab for re-study and may rejoin after qualifying
again. No manual qualification or promotion is required. Every strategy
remaining in the Manager is Active. The active count changes with
qualification; it has no fixed total.

RISK & CHRONOLOGICAL ANALYSIS (INFORMATIONAL ONLY)
-----------------------------------------------------
- The Strategy Match Details, Plan 1, Plan 2, and Analytics pages have
  cumulative profit, Maximum Drawdown and chronological-period panels.
- Maximum Drawdown is the largest historical peak-to-trough decline in
  chronological cumulative settled net starting from GH₵0, also expressible
  in GH₵100 betting units. It may change with registry filters and scope.
- Chronological evaluation is RETROSPECTIVE, not independently verified
  out-of-sample testing; rule discovery is not replayed at each cutoff.
- Walk-forward display eligibility by selected settled registry scope:
    Strategy Match Details: >=50; first half reference, five later periods.
    Plan 1: >=450; first 300 reference, five later periods >=30 each.
    Plan 2: >=50; first half reference, five later periods.
    Analytics: >=500; first 300 reference, five later periods >=40 each,
               with adjustments to avoid splitting a calendar date.
- Default analysis scope is registry filters across all pages; an optional
  current-visible-page scope is also available. Filtering only wins or
  losses changes the meaning of drawdown and return figures. Upcoming or
  unresolved matches are excluded from settled-return calculations.
- These displays DO NOT change strategy rules, Performance Score or the
  promotion/return lifecycle.

MOBILE HEADER AND SHARED NAVIGATION
-----------------------------------
- On each page the shared mobile header places the hamburger on the left and
  the football icon/name on the right; the menu opens the existing sidebar.
- Strategy Match Details also uses this header. Desktop sidebar unchanged.

PLAN ROUTING AND FINANCIAL DEFINITIONS
--------------------------------------
- Exactly one Active Manager trigger: Plan 1.
- Two or more Active Manager triggers: Plan 2.
- No Active trigger: excluded from both plans.
- Standard stake: GH₵100 per resolved bet. Win net: (odds − 1) × GH₵100.
  Loss net: −GH₵100.
- ROI = settled net P&L ÷ settled stake × 100. Upcoming and unresolved bets
  do not contribute to settled wins, losses, stake or ROI.
- Plan 2 grades each identical multi-strategy combination by the most frequent
  actual result in that group. A frequency tie uses the highest hypothetical
  GH₵100-stake net when there is a unique complete result; otherwise it stays
  unresolved.
- Analytics combines both plans and keeps the Plan label. Running balances
  use chronological settled net.

V2 SHADOW MODULES — SEPARATE FROM USER-FACING LIFECYCLE
-------------------------------------------------------
- The ZIP contains additional qualification_*_v2.py modules. The
  qualification_authority_v2.py component explicitly reports a shadow-only
  mode with live activation disabled. Do not confuse exploratory V2 gate
  diagnostics with the five browser-visible lifecycle criteria.
- This documentation update does not enable or change any qualification
  backend modules.

BACKUPS AND SAFE CHANGES
------------------------
- The service creates consistent database/workbook snapshots in data_backups
  before supported match or logo changes; it keeps up to 20 recent database
  and workbook snapshots in the project folder.
- Keep an additional copy outside the active project folder.
- SQLite is authoritative. A workbook-only copy is not a database restore.
  Stop the app before manually restoring SQLite.
- Notes JSON contains notes only; it does not include match data or Manager
  status. Browser storage can be lost if site data is cleared or another
  browser profile/app origin is used.

START THE DESKTOP APP
---------------------
On Windows, run START_FOOTBALL_ANALYTICS.bat from the project folder and keep
the launcher open. It starts desktop.py and the local service, normally at
http://127.0.0.1:8766. requirements.txt lists openpyxl and pywebview. Check
startup.log or run DIAGNOSE_STARTUP.bat if startup fails.

Use Data & Notes to review live record quality and sheet coverage. Its health
status summarizes the configured checks; it does not certify every source
value or strategy assumption.

MATCHES AUDIT REPAIRS — 10 NOVEMBER 2026
----------------------------------------
- Add, edit and delete now use serialized writes and validated workbook replacement.
- Edits/deletes require the loaded record revision. A stale screen receives a
  conflict instead of overwriting another device or recreating a deleted match.
- The app binds to 127.0.0.1 only. Desktop sessions are established by opening
  the app; API changes require a same-origin request. Direct LAN access is closed.
- The same launcher reuses/configures private Tailscale Serve and prints the
  HTTPS phone address. Phone access requires the same Tailscale account as the PC.
  It refuses public Funnel and will not replace another service's root route.
- The launcher stays running for phone access after the desktop window closes.
  Press Ctrl+C in the launcher to stop the service.
- If Excel synchronization fails, the database save is retained. Close Excel and
  use Retry workbook sync (Refresh also retries a known pending synchronization).
- Team/country logo uploads accept PNG, JPG, WEBP and GIF. Existing SVG team
  logos are retained but served with script execution disabled.
- A failed logo operation can be retried without resaving a match.
- The code/database recovery snapshots are in matches_fix_validation.
- Regression checks: python tests/test_matches_regression.py and
  node tests/test_match_utils.js. Browser results are in matches_fix_validation.

OFFLINE-FIRST PHASE 1 — VERIFIED READ-ONLY SNAPSHOT (12 NOVEMBER 2026)
------------------------------------------------------------------
The desktop remains the only authoritative Flask/SQLite server. This release
adds /offline-client.js, an expanded service worker, and a visible status strip
on all pages. When connected, the app securely stores the HTML/JS/CSS shell,
match registry (/api/matches), health, team/country logo mapping and available
logo images for offline viewing in the same browser origin. All cached figures
represent the most recent successful download, not guaranteed live data.

On a phone, install from the private Tailscale HTTPS address while connected,
keep it open until "offline copy ready" appears, and test with Tailscale/Internet
disconnected. The desktop localhost browser can continue working when the
internet is down, as long as the local Flask server is running.

PHASE 1 HISTORICAL NOTE (superseded by Phase 2): offline edits were not queued,
and bidirectional sync or conflict resolution did not exist. Server-based
strategy status remains authoritative. Direct offline API writes still fail.
Offline storage can be evicted; retain desktop database backups and follow
PWA_INSTALLATION_NOTES.txt for setup and limitations.


OFFLINE EDITING — PHASE 2 (12 Nov 2026)
See PWA_INSTALLATION_NOTES.txt and OFFLINE_PHASE2_RELEASE_NOTES.txt. Offline add/edit
forms save pending drafts in device-local IndexedDB. These drafts are not uploaded,
are not in the SQLite database, and do not alter strategy qualification or P&L.
Phase 3 now adds authenticated, idempotent ADD/EDIT synchronization. Offline drafts
are uploaded on reconnect while the app is open and the desktop private server
is reachable. Server validation detects duplicate IDs and stale edit revisions.
The desktop SQLite transaction also commits an operation receipt, so retries
cannot duplicate accepted changes. Conflicts remain device-local for manual
review; export them before clearing browser storage. The app reloads its
confirmed match data after sync; Strategy Manager browser-local state and
research notes are NOT synchronized between devices. Background sync when an
iPhone PWA is closed cannot be guaranteed. See OFFLINE_PHASE3_RELEASE_NOTES.txt
and PWA_INSTALLATION_NOTES.txt for testing and recovery instructions.

OFFLINE V1.1 — AUTOMATIC RECONNECTION REFRESH + SAFE OFFLINE DELETE (2026-11-12)
- On confirmed reconnection or an accepted offline operation, the open Matches registry now reloads its authoritative data without requiring a manual refresh. Other pages reload automatically where safe; an active editor defers reloading.
- A previously verified match can be QUEUED FOR DELETION offline. The existing desktop revision is required. A pending delete stays visible in the registry and retains all analytics until accepted by the master database, to avoid showing hypothetical results as real.
- The desktop checks original record revisions and commits deleted_matches tombstones and idempotent receipts atomically with deletes; stale or repeated operations cannot silently wipe new edits.
- IndexedDB pending drafts persist across upgrades; users must not clear browser data until all drafts have been safely synchronized or exported.
- Automatic synchronization happens while the app is open and desktop/Tailscale are reachable; it cannot be guaranteed with the browser fully closed. Offline logo changes and browser-local strategy metadata remain out of sync scope.

SOCCERRATING IMPORTER (2026-11-13, opt-in integration)
----------------------------------------------------
A new SoccerRating Importer page and separate review queue have been added.
Each strategy 2.00/2.05/2.10/2.15/2.20/2.25/2.30 maps to workbook Sheets 1–7.
Only upcoming Betting Picks (date, home/away teams and 1/X/2 odds) are
eligible for collection. League is optional at import approval and can be added later via Edit Match; missing logo uploads remain manual.
Previously saved team logos are reused automatically. The queue is stored in
soccerrating_queue.db (created on first run), separately from the master DB.
No collected match is saved into football_analytics.db or the workbook until
explicitly approved in the queue. Duplicate history survives restart.
An optional Edge/Playwright connector offers authorized account-session
collection with opt-in 60-minute checks, but has NOT been validated against
the owner's login or SoccerRating's exact private DOM. The connector remains
OFF until successful interactive verification. It does not bypass access
controls or restrictions; confirm source access permission before use.
Optional Android/iOS Web Push requires HTTPS, phone notification permission,
pywebpush/cryptography, and a local contact email configured in the importer.
New-match alerts are grouped by scan and created ONLY for newly discovered
fixtures. Notification history remains available even when push fails.
See SOCCERRATING_IMPORTER_SETUP_GUIDE.txt for requirements and limitations.
